<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

namespace app\services\store;


use app\dao\store\DeliveryServiceDao;
use app\model\order\StoreOrder;
use app\services\BaseServices;
use app\services\order\store\BranchOrderServices;
use app\services\message\service\StoreServiceLogServices;
use app\services\order\StoreOrderCartInfoServices;
use app\services\order\StoreOrderRefundServices;
use app\services\order\StoreOrderSplitServices;
use app\services\order\StoreOrderTakeServices;
use app\services\user\UserServices;
use crmeb\exceptions\AdminException;
use crmeb\services\FormBuilder;
use think\exception\ValidateException;
use think\facade\Db;
use app\controller\api\v1\order\StoreOrder as StoreOrders;


/**
 * 配送
 * Class DeliveryServiceServices
 * @package app\services\store
 * @mixin DeliveryServiceDao
 */
class DeliveryServiceServices extends BaseServices
{
    /**
     * 创建form表单
     * @var Form
     */
    protected $builder;
	//站内
    protected $prices = 2;
    protected $pricess = 0.03;

	//站外
	protected $outside_prices = 4;
	protected $outside_pricess = 0.05;

    /**
     * 构造方法
     * DeliveryServiceServices constructor.
     * @param DeliveryServiceDao $dao
     * @param FormBuilder $builder
     */
    public function __construct(DeliveryServiceDao $dao, FormBuilder $builder)
    {
        $this->dao = $dao;
        $this->builder = $builder;
    }

    /**
     * 获取配送员详情
     * @param int $id
     * @param string $field
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getDeliveryInfo(int $id, string $field = '*')
    {
        $info = $this->dao->getOne(['id' => $id, 'is_del' => 0], $field);
        if (!$info) {
            throw new ValidateException('配送员不存在');
        }
        return $info;
    }

	/**
	 * 根据uid获取配送员信息
	 * @param int $uid
	 * @param int $type
	 * @param int $relation_id
	 * @param array $field
	 * @return array|\think\Model
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 */
    public function getDeliveryInfoByUid(int $uid, int $type = -1, int $relation_id = -1, array $field = ['*'])
    {
        $where = ['uid' => $uid, 'is_del' => 0, 'status' => 1];
		if ($type != -1) {
			$where['type'] = $type;
		}
		if ($relation_id != -1) {
			$where['relation_id'] = $relation_id;
		}
        $info = $this->dao->get($where, $field);
        if (!$info) {
            throw new ValidateException('配送员不存在');
        }
        return $info;
    }

	/**
	 * 获取配送员所在门店id
	 * @param int $uid
	 * @param int $type
	 * @param string $field
	 * @param string $key
	 * @return array
	 */
    public function getDeliveryStoreIds(int $uid, int $type = 0, string $field = '*', string $key = '')
    {
        return $this->dao->getColumn(['uid' => $uid, 'type' => $type, 'is_del' => 0, 'status' => 1], $field, $key);
    }

    /**
     * 获取单个配送员统计信息
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function deliveryDetail(int $id)
    {
        $deliveryInfo = $this->getDeliveryInfo($id);
        if (!$deliveryInfo) {
            throw new AdminException('配送员不存在');
        }
        $where = ['store_id' => $deliveryInfo['store_id'], 'delivery_uid' => $deliveryInfo['uid']];
        /** @var BranchOrderServices $orderServices */
        $orderServices = app()->make(BranchOrderServices::class);
        $order_where = ['paid' => 1, 'refund_status' => [0, 3], 'is_del' => 0, 'is_system_del' => 0];

        $field = ['id', 'type', 'order_id', 'real_name', 'total_num', 'total_price', 'pay_price', 'FROM_UNIXTIME(pay_time,"%Y-%m-%d") as pay_time', 'paid', 'pay_type', 'activity_id', 'pink_id'];
        $list = $orderServices->getStoreOrderList($where + $order_where, $field, [], true);
        $data = ['id' => $id];
        $data['info'] = $deliveryInfo;
        $data['list'] = $list;
        $data['data'] = [
            [
                'title' => '待配送订单数',
                'value' => $orderServices->count($where + $order_where + ['status' => 2]),
                'key' => '单',
            ],
            [
                'title' => '已配送订单数',
                'value' => $orderServices->count($where + $order_where + ['status' => 3]),
                'key' => '单',
            ],
            [
                'title' => '待配送订单金额',
                'value' => $orderServices->sum($where + $order_where + ['status' => 2], 'pay_price', true),
                'key' => '元',
            ],
            [
                'title' => '已配送订单',
                'value' => $orderServices->sum($where + $order_where + ['status' => 3], 'pay_price', true),
                'key' => '元',
            ]
        ];
        return $data;
    }

    /**
     * 获取门店配送员订单统计
     * @param int $uid
     * @param int $store_id
     * @param string $time
     * @return array
     */
    public function getStoreData(int $uid, int $store_id, string $time = 'today')
    {
        $this->getDeliveryInfoByUid($uid, $store_id ? 1: 0, $store_id);
        $data = [];
        $where = ['delivery_uid' => $uid, 'time' => $time, 'paid' => 1, 'is_del' => 0, 'is_system_del' => 0, 'refund_status' => [0, 3]];
        if ($store_id) {
            $where['store_id'] = $store_id;
        }
        /** @var BranchOrderServices $order */
        $order = app()->make(BranchOrderServices::class);
        $where['status'] = 2;
        $data['unsend'] = $order->count($where);
        $where['status'] = 9;
        $data['send'] = $order->count($where);
        $data['send_price'] = $order->sum($where, 'pay_price', true);
        return $data;
    }

    /**
     * 获取配送员列表
     * @param array $where
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getServiceList(array $where)
    {
        [$page, $limit] = $this->getPageValue();
        $list = $this->dao->getServiceList($where, $page, $limit);
        $count = $this->dao->count($where);
        return compact('list', 'count');
    }

    /**
     * 获取配送员列表
     * @param int $type
     * @param int $store_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getDeliveryList(int $type = 0, int $relation_id = 0)
    {
        [$page, $limit] = $this->getPageValue();
        $where = ['status' => 1, 'is_del' => 0, 'type' => $type, 'relation_id' => $relation_id];
        $list = $this->dao->getServiceList($where, $page, $limit);
        foreach ($list as &$item) {
            if (!$item['nickname']) $item['nickname'] = $item['wx_name'];
        }
        $count = $this->dao->count($where);
        return compact('list', 'count');
    }

    /**
     * 创建配送员表单
     * @param array $formData
     * @return mixed
     * @throws \FormBuilder\Exception\FormBuilderException
     */
    public function createServiceForm(array $formData = [])
    {
        if ($formData) {
            $field[] = $this->builder->frameImage('avatar', '员工', $this->url(config('admin.admin_prefix') . '/widget.images/index', ['fodder' => 'avatar'], true), $formData['avatar'] ?? '')->icon('ios-add')->width('960px')->height('505px')->modal(['footer-hide' => true]);
        } else {
            $field[] = $this->builder->frameImage('image', '商城用户', $this->url(config('admin.admin_prefix') . '/system.user/list', ['fodder' => 'image'], true))->icon('ios-add')->width('960px')->height('550px')->modal(['footer-hide' => true])->Props(['srcKey' => 'image']);
            $field[] = $this->builder->hidden('uid', 0);
            $field[] = $this->builder->hidden('avatar', '');
        }
	    $field[] = $this->builder->select('type', '员工类型', $formData['status'] ?? 1)->setOptions([['value' => 3, 'label' => '配货员'],['value' => 4, 'label' => '收银员'], ['value' => 5, 'label' => '流转员'], ['value' => 6, 'label' => '配送员']]);
        $field[] = $this->builder->input('nickname', '员工名称', $formData['nickname'] ?? '')->required('请填写配送员名称')->col(24);
        $field[] = $this->builder->input('phone', '手机号码', $formData['phone'] ?? '')->required('请填写电话')->col(24)->maxlength(11);
        $field[] = $this->builder->radio('status', '员工状态', $formData['status'] ?? 1)->options([['value' => 1, 'label' => '显示'], ['value' => 0, 'label' => '隐藏']]);
	    return $field;


    }

    /**
     * 创建配送员获取表单
     * @return array
     * @throws \FormBuilder\Exception\FormBuilderException
     */
    public function create()
    {
        return create_form('添加配送员', $this->createServiceForm(), $this->url('/order/delivery/save'), 'POST');
    }

    /**
     * 编辑获取表单
     * @param int $id
     * @return array
     * @throws \FormBuilder\Exception\FormBuilderException
     */
    public function edit(int $id)
    {
        $serviceInfo = $this->dao->get($id);
        if (!$serviceInfo) {
            throw new AdminException('数据不存在!');
        }
        return create_form('编辑配送员', $this->createServiceForm($serviceInfo->toArray()), $this->url('/order/delivery/update/' . $id), 'PUT');
    }

    /**
     * 获取某人的聊天记录用户列表
     * @param int $uid
     * @return array|array[]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getChatUser(int $uid)
    {
        /** @var StoreServiceLogServices $serviceLog */
        $serviceLog = app()->make(StoreServiceLogServices::class);
        /** @var UserServices $serviceUser */
        $serviceUser = app()->make(UserServices::class);
        $uids = $serviceLog->getChatUserIds($uid);
        if (!$uids) {
            return [];
        }
        return $serviceUser->getUserList(['uid' => $uids], 'nickname,uid,avatar as headimgurl');
    }

    /**
     * 检查用户是否是配送员
     * @param int $uid
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkoutIsService(int $uid)
    {
        return (bool)$this->dao->count(['uid' => $uid, 'status' => 1, 'is_del' => 0]);
    }
	public function checkoutIs3Service(int $uid)
    {
        return (bool)$this->dao->count(['uid' => $uid, 'status' => 1, 'is_del' => 0, 'type' => 3]);
    }
	public function checkoutIs4Service(int $uid)
    {
        return (bool)$this->dao->count(['uid' => $uid, 'status' => 1, 'is_del' => 0, 'type' => 4]);
    }
	public function checkoutIs5Service(int $uid)
    {
        return (bool)$this->dao->count(['uid' => $uid, 'status' => 1, 'is_del' => 0, 'type' => 5]);
    }
	public function checkoutIs6Service(int $uid)
    {
        return (bool)$this->dao->count(['uid' => $uid, 'status' => 1, 'is_del' => 0, 'type' => 6]);
    }

    /**
     * 添加门店配送员
     * @return array
     * @throws \FormBuilder\Exception\FormBuilderException
     */
    public function createStoreDeliveryForm()
    {
        $field[] = $this->builder->frameImage('image', '商城用户', $this->url(config('admin.store_prefix') . '/system.User/list', ['fodder' => 'image'], true))->icon('ios-add')->width('960px')->height('450px')->modal(['footer-hide' => true])->Props(['srcKey' => 'image']);
        $field[] = $this->builder->hidden('uid', 0);
        $field[] = $this->builder->hidden('avatar', '');
        $field[] = $this->builder->input('nickname', '配送员名称')->required('请填写配送员名称')->col(24);
        $field[] = $this->builder->input('phone', '手机号码')->required('请填写电话')->col(24)->maxlength(11);
        $field[] = $this->builder->radio('status', '配送员状态', 1)->options([['value' => 1, 'label' => '显示'], ['value' => 0, 'label' => '隐藏']]);
        return create_form('添加门店配送员', $field, $this->url('/staff/delivery'));
    }

    /**
     * 编辑门店配送员
     * @return array
     * @throws \FormBuilder\Exception\FormBuilderException
     */
    public function updateStoreDeliveryForm($id, $formData)
    {
        $field[] = $this->builder->input('nickname', '配送员名称', $formData['nickname'] ?? '')->required('请填写配送员名称')->col(24);
        $field[] = $this->builder->frameImage('avatar', '配送员头像', $this->url(config('admin.store_prefix') . '/widget.images/index', ['fodder' => 'avatar'], true), $formData['avatar'] ?? '')->icon('ios-add')->width('960px')->height('505px')->modal(['footer-hide' => true]);
        $field[] = $this->builder->input('phone', '手机号码', $formData['phone'] ?? '')->required('请填写电话')->col(24)->maxlength(11);
        $field[] = $this->builder->radio('status', '配送员状态', $formData['status'] ?? 1)->options([['value' => 1, 'label' => '显示'], ['value' => 0, 'label' => '隐藏']]);
        return create_form('编辑门店配送员', $field, $this->url('/staff/delivery/' . $id), 'put');
    }

    /**
     * 获取配送员select（Uid）
     * @param array $where
     * @return mixed
     */
    public function getSelectList($where = [])
    {
        $list = $this->dao->getSelectList($where);
        $menus = [];
        foreach ($list as $menu) {
            $menus[] = ['value' => $menu['uid'], 'label' => $menu['nickname']];
        }
        return $menus;
    }

	//送水工 确认收货
	public function order_take_goods($order_id,$data){
		/** @var StoreOrders $StoreOrders */
		$StoreOrders = app()->make(StoreOrders::class);
		//站内送
		$tong_prices= Db::name ('config')->where ('key','tong_prices')->field ('value')->find ();
		$chaoshi_prices= Db::name ('config')->where ('key','chaoshi_prices')->field ('value')->find ();
		//站外送
		$outside_prices= Db::name ('config')->where ('key','outside_prices')->field ('value')->find ();
		$outside_pricess= Db::name ('config')->where ('key','outside_pricess')->field ('value')->find ();
		$this->prices=$tong_prices['value'];
		$this->pricess=$chaoshi_prices['value'];
		$this->outside_prices=$outside_prices['value'];
		$this->outside_pricess=$outside_pricess['value'];

		/** @var StoreOrder $StoreOrder */
		$StoreOrder = app()->make(StoreOrder::class);
		$where['order_id'] = ['eq', $order_id];
		$info = $StoreOrder->where($where)->find()->toArray ();
		/** @var StoreOrderRefundServices $storeOrderRefundServices */
		$storeOrderRefundServices = app()->make(StoreOrderRefundServices::class);

		$order=[];
		if ($info){
			if ($storeOrderRefundServices->count(['store_order_id' => $info['id'], 'refund_type' => [0, 1, 2, 4, 5, 6], 'is_cancel' => 0, 'is_del' => 0])) {
				throw new ValidateException('订单有售后申请请先处理');
			}
			if ($info['pid'] == -1) throw new ValidateException('订单已被拆分为多个订单，请刷新列表数据');

			if ($info['status']==1){
				$order['status'] = 2;
				if ($info['type']==11){
					$order['status'] = 3;
				}
				$order['distribution_status'] = 1;
				$order['authority_service'] = time();
				$order['confirm_time'] = time();
				$order['authority_confirm_img'] = $data['authority_confirm_img'];
				$order['confirm_kt_img'] = $data['confirm_kt_img'];
				$order['huitong'] = $data['huitong'];  //拿回来多少桶
				$order['replenishment'] = $data['replenishment'];   //补桶
				$order['my_kt_img'] = $data['my_kt_img'];//自有张照片
				$order['refund_img'] = $data['refund_img']; //退水照片
				$order['refund_water'] = $data['refund_water']; //退水  数量
				$order['authority_remark']= $data['authority_remark']; //  备注
				$order['songsui_count'] = $data['songsui_count']; //  送水数量

			}elseif($info['status']>=2||$info['distribution_status']==1){
				return ['status' => true,'msg' => '送货成功'];
			}elseif($info['status']==0){
				return ['status' => false,'msg' => '此订单没有被接单'];
			}

            if ($info['address_ids']==1){
                $distribution_price=$this->prices;
            }else{
                $distribution_price = $this->outside_prices;
            }
			Db::startTrans ();
			try {
//				/** @var StoreOrderCartInfoServices $orderInfoServices */
//				$orderInfoServices = app()->make(StoreOrderCartInfoServices::class);
//				$storeName = $orderInfoServices->getCarIdByProductTitle((int)$info['id']);
//				$storeTitle = substrUTf8($storeName, 20, 'UTF-8', '');
//				if ($info['uid']&&$info['type']!=11&&$info['type']!=12&&$info['type']!=14) {
//					/** @var UserServices $userServices */
//					/** @var StoreOrderTakeServices $StoreOrderTakeServices */
//					$userServices = app()->make(UserServices::class);
//					$StoreOrderTakeServices = app()->make(StoreOrderTakeServices::class);
//					$userInfo = $userServices->get((int)$info['uid']);
//					$res = $this->transaction(function () use ($info, $userInfo, $storeTitle,$StoreOrderTakeServices) {
//						//赠送积分
//						$res1 = $StoreOrderTakeServices->gainUserIntegral($info, $userInfo, $storeTitle);
//						//返佣
//						$res2 = $StoreOrderTakeServices->backOrderBrokerage($info, $userInfo);
//						//经验
//						$res3 = $StoreOrderTakeServices->gainUserExp($info, $userInfo);
//						if (!($res1 && $res2 && $res3)) {
//							throw new ValidateException('收货失败!');
//						}
//					}, true);
//				}
				$now_water_quantity=Db::name ('water_user')->where ('uid',$info['uid'])->field ('now_water_quantity,lock_kt_pledge,my_kt_ktpledge,kt_pledge')->find ();
				if (!$now_water_quantity){
					$now_water_quantity['now_water_quantity']=0;
					$now_water_quantity['lock_kt_pledge']=0;
					$now_water_quantity['my_kt_ktpledge']=0;
					$now_water_quantity['kt_pledge']=0;
					$now_water_quantity['uid']=$info['uid'];
					Db::name ('water_user')->insert ($now_water_quantity);
				}
				if ($info['set_type']==1&&$info['type']<12&&$info['product_type']==0){  //水站   桶装水
					//查询用户当前空桶数量 和 通押金数量
					if ($info['type']<12){

						//用户手里有多少桶        $now_water_quantity['now_water_quantity'];

						$water = $data['songsui_count']-$data['refund_water'];///给了用户多少桶装水

						// 本次送的桶装水 -  回收回来的空桶就是  就是用户手里有多少桶
						$waters  = $water - $data['huitong'];

						$water_quantity = $now_water_quantity['now_water_quantity']+$waters;
						if ($water_quantity<0){
							Db ::rollback ();
							return ['status' => false,'msg' => '回收空桶不能超过用户应有数量'];
						}
						Db::name ('water_user')->where ('uid',$info['uid'])->update(['now_water_quantity'=>$water_quantity]);
						$kt_pledge = $now_water_quantity['kt_pledge']+$now_water_quantity['my_kt_ktpledge'];

						if ($water_quantity>$kt_pledge){
							Db ::rollback ();
							$noe_water_=$water_quantity-$kt_pledge;
							return ['status' => false,'msg' => '用户需要购买桶押金'.$noe_water_.'个'];
						}
						$songshui=$data['songsui_count'];
						//解锁空桶押金数量
						if ($now_water_quantity['lock_kt_pledge']<$songshui){
							$datalock_kt_pledge['lock_kt_pledge'] = 0;
							Db::name ('water_user')->where ('uid',$info['uid'])->update($datalock_kt_pledge);
						}else{
							Db::name ('water_user')->where ('uid',$info['uid'])->Dec('lock_kt_pledge',$songshui)->update ();
						}

					}

				}
				if ($data['refund_water']>0&&$data['type']==11){
					$refund_water_number=$data['refund_water'];
					$water_tickets = Db ::name ('water_ticket') -> where ('order_sn', $order_id) -> find ();

					$ticket = Db ::name ('water_ticket')
						-> where ('goods_id', $water_tickets[ 'goods_id' ])
						-> where ('user_id', $water_tickets[ 'user_id' ])
						-> order ('id desc')
						-> find ();

					$num = 0;
					if ($ticket) {
						$num = $ticket[ 'num' ] + $refund_water_number;
					}
					$water_ticket[ 'order_sn' ] = $order_id;
					$water_ticket[ 'user_id' ] = $ticket[ 'user_id' ];
					$water_ticket[ 'goods_id' ] = $ticket[ 'goods_id' ];
					$water_ticket[ 'type' ] = 1;
					$water_ticket[ 'nums' ] = $refund_water_number;
					$water_ticket[ 'createtime' ] = time ();
					$water_ticket[ 'num' ] = $num;
					$water_ticket[ 'remark' ] = '退回水票' . $refund_water_number . "张";
					Db ::name ('water_ticket') -> insert ($water_ticket);
				}

				$StoreOrder->where($where)->save($order);

				$date = date('Y-m');
				$dates = date('Y-m-d H:i:s');
				$dated = date('Y-m-d ');
				/** @var StoreOrderCartInfoServices $StoreOrderCartInfoServices */
				$StoreOrderCartInfoServices =app()->make(StoreOrderCartInfoServices::class);
				//超市提成
				if ($info['set_type']==2){
					$res=$StoreOrderCartInfoServices->getOrderCartInfo ($info['id']);
					$performance=0;
					foreach ($res as $k => $v ){
						if ($v['cart_info']['is_gift']==1){
							continue;
						}
						$performance += $v['cart_info']['cart_num']-$v['cart_info']['refund_num'];
					}
                    if ($info['address_ids']==1){
                        $price = $info['pay_price']*$this->pricess;
                    }else{
                        $price = $info['pay_price']*$this->outside_pricess;
                    }

					Db::name('worker_examine')->insert(['time'=>$date,'user_id'=>$info['delivery_uid'],'single_quantity'=>1,'performance'=>$performance,'Bad'=>0,'esteem'=>0,'substract'=>0,'ticheng'=>(float)$price,'times'=>$dates,'timed'=>$dated,'order_id'=>$order_id]);
				}

				//一键送水  和 送 桶装水
				if ($info['set_type']==1){
					if ($info['type']==11){

						$res=$StoreOrderCartInfoServices->getOrderCartInfo ($info['id']);
						$performance=0;
						$price=0;
							$performance += $water;
							$num         =  $water;
							$price       += $num * $distribution_price;

						Db::name('worker_examine')->insert(['time'=>$date,'user_id'=>$info['delivery_uid'],'single_quantity'=>1,'performance'=>$performance,'Bad'=>0,'esteem'=>0,'substract'=>0,'ticheng'=>(float)$price,'times'=>$dates,'timed'=>$dated,'order_id'=>$order_id]);
					}

					if ($info['type']==0&&$info['product_type']==0){

						$res=$StoreOrderCartInfoServices->getOrderCartInfo ($info['id']);
						$performance=0;
						$price=0;
						foreach ($res as $k => $v ){

							$performance += $v['cart_info']['cart_num'];
							$num         =  $v['cart_info']['cart_num'];
							$price       += $num * $distribution_price;
						}
						Db::name('worker_examine')->insert(['time'=>$date,'user_id'=>$info['delivery_uid'],'single_quantity'=>1,'performance'=>$performance,'Bad'=>0,'esteem'=>0,'substract'=>0,'ticheng'=>(float)$price,'times'=>$dates,'timed'=>$dated,'order_id'=>$order_id]);
					}
					if ($info['type']==0&&$info['product_type']==7){

						$res=$StoreOrderCartInfoServices->getOrderCartInfo ($info['id']);
						$performance=0;
						$price=0;
						foreach ($res as $k => $v ){

							$performance += $v['cart_info']['cart_num'];
							$num         =  $v['cart_info']['cart_num'];
							$price       += $num * $distribution_price;
						}
						Db::name('worker_examine')->insert(['time'=>$date,'user_id'=>$info['delivery_uid'],'single_quantity'=>1,'performance'=>$performance,'Bad'=>0,'esteem'=>0,'substract'=>0,'ticheng'=>(float)$price,'times'=>$dates,'timed'=>$dated,'order_id'=>$order_id]);
					}

					if ($info['product_type']==101){

						$res=$StoreOrderCartInfoServices->getOrderCartInfo ($info['id']);
						$performance=0;
						foreach ($res as $k => $v ){
							if ($v['cart_info']['is_gift']==1){
								continue;
							}
							$performance += $v['cart_info']['cart_num']-$v['cart_info']['refund_num'];
						}
						$price = $performance*$distribution_price;

						Db::name('worker_examine')->insert(['time'=>$date,'user_id'=>$info['delivery_uid'],'single_quantity'=>1,'performance'=>$performance,'Bad'=>0,'esteem'=>0,'substract'=>0,'ticheng'=>(float)$price,'times'=>$dates,'timed'=>$dated,'order_id'=>$order_id]);
					}
                    if ($info['product_type']==100){

						$res=$StoreOrderCartInfoServices->getOrderCartInfo ($info['id']);
						$performance=0;
						foreach ($res as $k => $v ){
							if ($v['cart_info']['is_gift']==1){
								continue;
							}
							$performance += $v['cart_info']['cart_num']-$v['cart_info']['refund_num'];
						}
                        if ($info['address_ids']==1){
                            $price = $info['pay_price']*$this->pricess;
                        }else{
                            $price = $info['pay_price']*$this->outside_pricess;
                        }

						Db::name('worker_examine')->insert(['time'=>$date,'user_id'=>$info['delivery_uid'],'single_quantity'=>1,'performance'=>$performance,'Bad'=>0,'esteem'=>0,'substract'=>0,'ticheng'=>(float)$price,'times'=>$dates,'timed'=>$dated,'order_id'=>$order_id]);
					}
				}
                //退空桶押金
				if ($info['type']==12){

//					$price=0;
//					$price += $data['huitong'] * 2;
//
//					Db::name('worker_examine')->insert(['time'=>$date,'user_id'=>$info['delivery_uid'],'single_quantity'=>1,'performance'=>$data['huitong'],'Bad'=>0,'esteem'=>0,'substract'=>0,'ticheng'=>(float)$price,'times'=>$dates,'timed'=>$dated,'order_id'=>$order_id]);
					//增加用户家里应该右的数量
					if ($data['huitong']< $info['now_water_quantity_frozen']){

						$now_water_quantity_frozen=$info['now_water_quantity_frozen']-$data['huitong'];

//						Db::name ('water_user')->where ('uid',$info['uid'])->update(['kt_pledge'=>$now_water_quantity['kt_pledge']+$now_water_quantity_frozen]);

							Db::name ('water_user')->where ('uid',$info['uid'])->update(['now_water_quantity'=>$now_water_quantity['now_water_quantity']+$now_water_quantity_frozen]);

					}

					$refund = Db::name ('store_order_refund')->where('id',$info['refund_id'])->find ();
					Db::name ('store_order_refund')->where('id',$info['refund_id'])->update(['refund_type'=>5]);
					if ($refund['refund_num'] > $data['tui_count']){
						Db::name ('water_user')->where ('uid',$info['uid'])->update(['kt_pledge'=>$now_water_quantity['kt_pledge']+($refund['refund_num']-$data['tui_count'])]);

//						Db::name ('store_order_refund')->where('id',$info['refund_id'])->update(['remark'=>'退空桶押金少退'.$nums.'桶']);
						$cart_info = json_decode ($refund['cart_info'],true);
						/** @var StoreOrderSplitServices $storeOrderSpliteServices */
						$storeOrderSpliteServices = app()->make(StoreOrderSplitServices::class);
						$cart_infos = $storeOrderSpliteServices->getSplitOrderCartInfo_2($refund['store_order_id'],[['cart_id'=>$cart_info[0]['id'],'cart_num'=>$data['tui_count']]]);



						Db::name ('store_order_refund')->where('id',$info['refund_id'])->update(['cart_info'=>json_encode($cart_infos,true),'refund_num'=>$data['tui_count'],'refund_price'=>$cart_info[0]['productInfo']['price']* $data['tui_count']]);

						Db::name ('store_order_cart_info')->where('oid',$refund['store_order_id'])->update(['refund_num'=>$data['tui_count']]);
					}
				}

				if ($info['type']==14){
					$res =$this->tuihuo_ok ($info['refund_id'],$info);

					if ($res['status']==false){
						Db ::rollback ();
						return ['status' => false,'msg' => '此订单已完成'];
					}
				}
				if ($info['type']!='14'&&$info['type']!='12'){
					if ($info['is_channel']==1){
						/** @var StoreOrderTakeServices $services **/
						$services = app()->make(StoreOrderTakeServices::class);
						$services->storeProductOrderUserTakeDelivery($info);
					}elseif ($info['is_channel']==4){
						$StoreOrders->umengPushMsgs_app($info['uid']);
					}

				}
				Db ::commit ();
			} catch (\Exception $e) {
				Db ::rollback ();
				$result[ 'msg' ] = $e -> getMessage ().$e->getFile().$e->getLine();
				$result[ 'status' ] = false;
				return $result;
			}
			return ['status' => true, 'msg' => '送货成功'];
		}
	}



	public function slpitComputeOrderCart(int $cart_num, array $cart_info, int $i = 0, bool $is_gift = false)
	{
		if (!$cart_num || !$cart_info) return [];
		$new_cart_info = $cart_info;
		if ($cart_num < $cart_info['cart_num']) {
			$compute_arr = ['coupon_price', 'integral_price', 'postage_price', 'use_integral', 'one_brokerage', 'two_brokerage', 'sum_true_price', 'first_order_price'];
			foreach ($compute_arr as $field) {
				if (!isset($cart_info[$field]) || !$cart_info[$field] || $is_gift) {
					$new_cart_info[$field] = 0;
					continue;
				}
				$scale = 2;
				if ($field == 'use_integral') $scale = 0;

				if (!$i) {//拆出
					$new_cart_info[$field] = bcmul((string)$cart_num, bcdiv((string)$cart_info[$field], (string)$cart_info['cart_num'], 4), $scale);
				} else {
					$field_number = bcmul((string)bcsub((string)$cart_info['cart_num'], (string)$cart_num, 0), bcdiv((string)$cart_info[$field], (string)$cart_info['cart_num'], 4), $scale);
					$new_cart_info[$field] = bcsub((string)$cart_info[$field], (string)$field_number, $scale);
				}
			}
		}
		$new_cart_info['cart_num'] = $cart_num;
		return $new_cart_info;
	}
	//退换货
	public  function tuihuo_ok($id,$info)
	{
		$refund = Db::name ('store_order_refund')->where('id',$id)->find ();
		$order= Db::name ('store_order')->where('id',$refund['store_order_id'])->find ();
		if ($refund['refund_type']==4){
			//退货提成
			if ($order['set_type']==2){
				$date = date('Y-m');
				$dates = date('Y-m-d H:i:s');
				$dated = date('Y-m-d ');
				$performance=0;
				$price=0;
				Db::name ('store_order_refund')->where('id',$id)->update(['refund_type'=>5]);
				foreach (json_decode ($refund['cart_info']) as $k=>$v){
					$v= get_object_vars($v);
					$v['productInfo']= get_object_vars($v['productInfo']);
					$performance += $v['cart_num'];
					$num =$v['cart_num'];
					$price += $num * $v['productInfo']['price']*0.02;
				}
//				Db::name('worker_examine')->insert(['time'=>$date,'user_id'=>$info['delivery_uid'],'single_quantity'=>1,'performance'=>$performance,'Bad'=>0,'esteem'=>0,'substract'=>0,'ticheng'=>(float)$price,'times'=>$dates,'timed'=>$dated,'order_id'=>$info['order_id']]);
			}
			if($order['set_type']==1){
				$date = date('Y-m');
				$dates = date('Y-m-d H:i:s');
				$dated = date('Y-m-d ');
				$performance=0;
				$price=0;
				Db::name ('store_order_refund')->where('id',$id)->update(['refund_type'=>5]);
				foreach (json_decode ($refund['cart_info']) as $k=>$v){
					$v= get_object_vars($v);
					$v['productInfo']= get_object_vars($v['productInfo']);
					$num =$v['cart_num'];
					$performance += $num;
					$price += $num * 2;
				}
//				Db::name('worker_examine')->insert(['time'=>$date,'user_id'=>$info['delivery_uid'],'single_quantity'=>1,'performance'=>$performance,'Bad'=>0,'esteem'=>0,'substract'=>0,'ticheng'=>(float)$price,'times'=>$dates,'timed'=>$dated,'order_id'=>$info['order_id']]);
			}
//
		}elseif ($refund['refund_type']==5){
			return ['status' => false,'msg' => '此订单已完成'];
		}
		return ['status' => true];
	}
}
